<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Request;

/**
 * 首页
 */
class NewHome extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /*
     * 金刚区详情
     */
    public function jingang_show()
    {
        $id = $this->request->param('id');
        $jin = Db::name("jingang_anew")->where('id', $id)->find();
        $list = Db::name("goods")
            ->where("status = 1")
            ->where("is_del = 0")
            ->where("jingang_id", $id)
            ->order('jinIndex', 'desc')
            ->order('jinIndexTime', 'asc')
            ->order('createtime', 'asc')
            ->field("id,name,image,price,old_price,vip_price,sale_num,integral,province,city,vip_price")
            ->paginate(10);
        $goods = $list->items();
        foreach ($goods as $k => $v) {
            $goods[$k]['image'] = path($v['image']);
            preg_match_all("/./us", $v['name'], $match);
            $goods[$k]['length'] = count($match[0]);
            if ($goods[$k]['length'] > 10) {
                $goods[$k]['height'] = 536;
            } else {
                $goods[$k]['height'] = 500;
            }
        }
        $jin['image'] = path($jin['image']);
        $jin['beijing_image'] = path($jin['beijing_image']);
        $jin['goodList'] = $goods;
        $this->success('成功', $jin, 200);
    }

    public function boom()
    {
        $boom = Db::name("activity_bomb")->find();
        $this->success('成功', $boom, 200);
    }

    public function boom_good()
    {
        $boom = Db::name("activity_bomb")->where('status', 1)->find();
//        if (!$boom) {
//            $this->error('每日爆款已下架', null, 303);
//        }
        $list = Db::name("goods")
            ->where("status = 30")
            ->where("is_del = 0")
            ->order('bombIndex', 'desc')
            ->order('bombIndexTime', 'desc')
            ->order('createtime', 'desc')
            ->field("id,name,image,vip_price as price,sale_num,integral,province,city,bombImage")
            ->paginate(10);
        $goods = $list->items();
        foreach ($goods as $k => $v) {
            $goods[$k]['image'] = path($v['image']);
            $goods[$k]['bombImage'] = path($v['bombImage']);
            preg_match_all("/./us", $v['name'], $match);
            $goods[$k]['length'] = count($match[0]);
            if ($goods[$k]['length'] > 10) {
                $goods[$k]['height'] = 536;
            } else {
                $goods[$k]['height'] = 500;
            }
        }
        $jin['goodList'] = $goods;
        $this->success('成功', $jin, 200);
    }

    public function boom_good_detail()
    {
        $request = [
            'goods_id' => $this->request->param('goods_id'),//商品id
            'uid' => $this->request->param('uid'),//
        ];
        /* 验证不能为空的字段*/
        $EmptyData = array('goods_id');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $request);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $uid = $request['uid'];
        $goods_id = $request['goods_id'];
        $goods = Db::name("goods")
            ->where("id = {$goods_id}")
            ->where("status = 30")
            ->where("is_del = 0")
            ->field("id,name,price,bombImage,old_price,sale_num,image,images,introduce,chandi,goods_one_type_id,brand,parameter,zhongliang,expressfee_id,is_baoyou,status,is_del,spec1,spec2,content,integral,province,city,vip_price")
            ->find();
        if (!$goods) {
            $this->error('该商品已下架每日爆款', '', 303);
        }
        $goods['price'] = $goods['vip_price'];
        $goods['bombImage'] = path($goods['bombImage']);
        unset($goods['vip_price']);
        $data = $this->goodDetail($goods, $uid);
        $this->success('成功', $data, 200);
    }

    public function boom_good_stock(Request $request)
    {
        $request = [
            'goods_id' => $this->request->param('goods_id'),//
            'goods_spec_one_id' => $this->request->param('goods_spec_one_id'),//
            'goods_spec_two_id' => $this->request->param('goods_spec_two_id')
        ];
        /* 验证不能为空的字段*/
        $EmptyData = array('goods_id', 'goods_spec_one_id');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $request);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $goods_id = $request['goods_id'];
        $goods_spec_one_id = $request['goods_spec_one_id'];
        $goods_spec_two_id = $request['goods_spec_two_id'];
        $data = $this->goodStockDetail($goods_id, $goods_spec_one_id, $goods_spec_two_id);
        foreach ($data as $k => $v) {
            $data[$k]['price'] = $v['vip_price'];
        }
        $this->success('成功', $data, 200);
    }

    public function kill()
    {
        $kill = Db::name("activity_kill")->find();
        if (isset($kill['killStartTime'])) {
            if (strtotime($kill['killStartTime']) >= strtotime(date("Y-m-d H:i:s"))) {
                $kill['status'] = 0;
            }
        }
        if (isset($kill['killEndTime'])) {
            if (strtotime($kill['killEndTime']) <= strtotime(date("Y-m-d H:i:s"))) {
                $kill['status'] = 0;
            }
        }
        $kill['countDown'] = strtotime($kill['killEndTime']) - time();
        if ($kill['countDown'] < 0) {
            $kill['countDown'] = 0;
        }
        $this->success('成功', $kill, 200);
    }

    public function kill_good()
    {
        $kill = Db::name("activity_kill")->find();
//        if(isset($kill['killStartTime'])){
//            if(strtotime($kill['killStartTime']) >= strtotime(date("Y-m-d H:i:s"))){
//                $this->error('限时秒杀未开始', null, 303);
//            }
//        }
//        if(isset($kill['killEndTime'])){
//            if(strtotime($kill['killEndTime']) <= strtotime(date("Y-m-d H:i:s"))){
//                $this->error('限时秒杀已结束', null, 303);
//            }
//        }
//        if (!$kill['status']) {
//            $this->error('限时秒杀已结束', null, 303);
//        }
        $list = Db::name("goods")
            ->where("status = 40")
            ->where("is_del = 0")
            ->order('killIndex', 'desc')
            ->order('killIndexTime', 'desc')
            ->order('createtime', 'desc')
            ->field("id,name,image,price,sale_num,integral,province,city,killStartTime,killEndTime,idNum")
            ->paginate(10);
        $goods = $list->items();
        foreach ($goods as $k => $v) {
            $goods[$k]['image'] = path($v['image']);
            preg_match_all("/./us", $v['name'], $match);
            $goods[$k]['length'] = count($match[0]);
            if ($goods[$k]['length'] > 10) {
                $goods[$k]['height'] = 536;
            } else {
                $goods[$k]['height'] = 500;
            }
            $countDown = 0;
            if ($v['killEndTime'] <= date("Y-m-d H:i:s")) {
                $killStatus = 2;
            } else if ($v['killStartTime'] >= date("Y-m-d H:i:s")) {
                $countDown = strtotime($v['killEndTime']) - strtotime(date("Y-m-d H:i:s"));
                $killStatus = 1;
            } else {
                $killStatus = 0;
            }
            $goods[$k]['killStatus'] = $killStatus;
            $goods[$k]['countDown'] = $countDown;
        }
        $jin['goodList'] = $goods;
        $this->success('成功', $jin, 200);
    }

    public function kill_good_detail()
    {
        $kill = Db::name("activity_kill")->find();
//        if(isset($kill['killStartTime'])){
//            if(strtotime($kill['killStartTime']) >= strtotime(date("Y-m-d H:i:s"))){
//                $kill['status'] = 0;
//            }
//        }
//        if(isset($kill['killEndTime'])){
//            if(strtotime($kill['killEndTime']) <= strtotime(date("Y-m-d H:i:s"))){
//                $kill['status'] = 0;
//            }
//        }
//        if (!$kill['status']) {
//            $this->error('限时秒杀已结束', null, 303);
//        }
        $request = [
            'goods_id' => $this->request->param('goods_id'),//商品id
            'uid' => $this->request->param('uid'),//
        ];
        /* 验证不能为空的字段*/
        $EmptyData = array('goods_id');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $request);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $uid = $request['uid'];
        $goods_id = $request['goods_id'];
        $goods = Db::name("goods")
            ->where("id = {$goods_id}")
            ->where("status = 40")
            ->where("is_del = 0")
            ->field("id,name,price,old_price,sale_num,image,images,introduce,chandi,goods_one_type_id,brand,parameter,zhongliang,expressfee_id,is_baoyou,status,is_del,spec1,spec2,content,integral,province,city,vip_price,
                killStartTime,killEndTime,idNum")
            ->find();
        if (!$goods) {
            $this->error('该商品已下架限时秒杀', '', 303);
        }
        $countDown = 0;
        if ($goods['killEndTime'] <= date("Y-m-d H:i:s")) {
            $killStatus = 2;
        } else if ($goods['killStartTime'] >= date("Y-m-d H:i:s")) {
            $countDown = strtotime($goods['killEndTime']) - strtotime(date("Y-m-d H:i:s"));
            $killStatus = 1;
        } else {
            $killStatus = 0;
        }
        $goods['killStatus'] = $killStatus;
        $goods['countDown'] = $countDown;
        unset($goods['vip_price']);
        $data = $this->goodDetail($goods, $uid);
        $this->success('成功', $data, 200);
    }

    public function kill_good_stock(Request $request)
    {
        $request = [
            'goods_id' => $this->request->param('goods_id'),//
            'goods_spec_one_id' => $this->request->param('goods_spec_one_id'),//
            'goods_spec_two_id' => $this->request->param('goods_spec_two_id')
        ];
        /* 验证不能为空的字段*/
        $EmptyData = array('goods_id', 'goods_spec_one_id');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $request);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $goods_id = $request['goods_id'];
        $goods_spec_one_id = $request['goods_spec_one_id'];
        $goods_spec_two_id = $request['goods_spec_two_id'];
        $data = $this->goodStockDetail($goods_id, $goods_spec_one_id, $goods_spec_two_id);
        $this->success('成功', $data, 200);
    }

    //立即购买生成订单
    public function boom_create_order()
    {
        $request = Request::instance();
        $userId = $request->param("userhome_id");
        $data = [
            'goods_spec_one_id' => $request->param("goods_spec_one_id"),//商品属性id
            'goods_spec_two_id' => $request->param("goods_spec_two_id"),//商品属性id
            'num' => $request->param("num"),//商品数量
            'address_id' => $request->param("address_id"),//地址id
            'paytype' => $request->param("paytype"),//地址id
        ];
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $EmptyData = array('goods_spec_one_id', 'goods_spec_two_id', 'num', 'address_id', 'paytype');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $data);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $car = [];
        $car['userhome_id'] = $userId;
        $car['goods_spec_one_id'] = $data['goods_spec_one_id'];
        $car['goods_spec_two_id'] = $data['goods_spec_two_id'];
        $car['num'] = $data['num'];
        $data['buy_car_id'] = DB::name('buy_car')->insertGetId($car);
        $newOrder = new NewOrder();
        $res = $newOrder->getCarGoods($data, $userId, 30);
        DB::name('buy_car')->where('id', 'in', $data['buy_car_id'])->delete();
        //返回支付单号
        $this->success('OK', $res, 200);
    }

    //立即购买生成订单
    public function kill_create_order()
    {
        $kill = Db::name("activity_kill")->find();
        if (isset($kill['killStartTime'])) {
            if (strtotime($kill['killStartTime']) >= strtotime(date("Y-m-d H:i:s"))) {
                $kill['status'] = 0;
            }
        }
        if (isset($kill['killEndTime'])) {
            if (strtotime($kill['killEndTime']) <= strtotime(date("Y-m-d H:i:s"))) {
                $kill['status'] = 0;
            }
        }
        if (!$kill['status']) {
            $this->error('限时秒杀已结束', null, 303);
        }
        $request = Request::instance();
        $userId = $request->param("userhome_id");
        $data = [
            'goods_spec_one_id' => $request->param("goods_spec_one_id"),//商品属性id
            'goods_spec_two_id' => $request->param("goods_spec_two_id"),//商品属性id
            'num' => $request->param("num"),//商品数量
            'address_id' => $request->param("address_id"),//地址id
            'paytype' => $request->param("paytype"),//地址id
        ];
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $EmptyData = array('goods_spec_one_id', 'goods_spec_two_id', 'num', 'address_id', 'paytype');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $data);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $good = DB::name('goods t1')
            ->join('goods_spec_one t2', 't1.id = t2.goods_id')
            ->where('t2.id', $data['goods_spec_one_id'])
            ->where('t1.status', 40)
            ->field("t1.idNum,t1.id,t1.killCreateTime")
            ->find();
        if (!$good) {
            $this->error('您的购买次数已满');
        }
        $orderSql = DB::name('order t1')
            ->join('orderdetail t2', 't1.id = t2.order_id')
            ->where('t2.goods_id', $good['id'])
            ->where('t1.userhome_id', $userId);
        if (isset($good['killCreateTime'])) {
            $orderSql->where('createtime', ">=", strtotime($good['killCreateTime']));
        }
        $orderNum = $orderSql
            ->whereRaw('t1.status != 0')
            ->sum('num');
        if ($good['idNum'] < ($orderNum + $data['num'])) {
            $this->error('已超过限购次数', null, 303);
        }
        $car = [];
        $car['userhome_id'] = $userId;
        $car['goods_spec_one_id'] = $data['goods_spec_one_id'];
        $car['goods_spec_two_id'] = $data['goods_spec_two_id'];
        $car['num'] = $data['num'];
        $data['buy_car_id'] = DB::name('buy_car')->insertGetId($car);
        $newOrder = new NewOrder();
        $res = $newOrder->getCarGoods($data, $userId, 40);
        DB::name('buy_car')->where('id', 'in', $data['buy_car_id'])->delete();
        //返回支付单号
        $this->success('OK', $res, 200);
    }


    private function goodStockDetail($goods_id, $goods_spec_one_id, $goods_spec_two_id)
    {
        $sql = Db::name("goods_stock a")
            ->join('goods_spec_one c', 'a.goods_spec_one_id = c.id')
            ->join('goods_spec_two d', 'a.goods_spec_two_id = d.id', "LEFT")
            ->where("a.goods_id = {$goods_id}")
            ->where("a.goods_spec_one_id = {$goods_spec_one_id}");
        if (isset($goods_spec_two_id) && !empty($goods_spec_two_id)) {
            $sql->where("a.goods_spec_two_id = {$goods_spec_two_id}");
        }
        $data = $sql->field("a.id,a.goods_id,a.goods_spec_one_id,c.name goods_spec_one_name,a.goods_spec_two_id,d.name goods_spec_two_name,a.num,a.price,a.image,a.use_integral,vip_price")
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['image'] = path($v['image']);
            $data[$k]['integral'] = $v['use_integral'];
        }
        return $data;
    }

    private function goodDetail($goods, $uid)
    {
        $goods_id = $goods['id'];
        if ($uid) {
            $userLink = Db::name("user_link")->where("userId = $uid")->find();
            if (!$userLink) {
                $userLink = [];
                $userLink['userId'] = $uid;
                $userLink['goodsOneTypeIdList'] = $goods['goods_one_type_id'];
                Db::name("user_link")->insert($userLink);
            } else {
                if (isset($userLink['goodsOneTypeIdList']) && !empty($userLink['goodsOneTypeIdList'])) {
                    $goodsOneTypeIdList = explode(';', $userLink['goodsOneTypeIdList']);
                    if (count($goodsOneTypeIdList) >= 5) {
                        unset($goodsOneTypeIdList[4]);
                        $goodsOneTypeIdList = $goods['goods_one_type_id'] . ";" . implode(';', $goodsOneTypeIdList);
                    } else {
                        $goodsOneTypeIdList = $goods['goods_one_type_id'] . ";" . $userLink['goodsOneTypeIdList'];
                    }
                } else {
                    $goodsOneTypeIdList = $goods['goods_one_type_id'];
                }
                Db::name("user_link")->where("userId = $uid")->update(['goodsOneTypeIdList' => $goodsOneTypeIdList]);
            }
        }
        $goods['content'] = content_url($goods['content']);
        $goods['image'] = path($goods['image']);
        $images = explode(',', $goods['images']);
        $image = array();
        foreach ($images as $kk => $vv) {
            $image[] = path($vv);
        }
        $goods['images'] = $image;
        //属性
        $kucun = Db::name("goods_stock")->where("goods_id = {$goods_id}")->select();
        $goods_spec_one_id = array();
        $goods_spec_two_id = array();
        foreach ($kucun as $k => $v) {
            $goods_spec_one_id[] = $v['goods_spec_one_id'];
            $goods_spec_two_id[] = $v['goods_spec_two_id'];
        }
        $goods_spec_one_id = implode(',', $goods_spec_one_id);
        $goods_spec_two_id = implode(',', $goods_spec_two_id);
        $goods_spec_one = array();
        if ($goods_spec_one_id) {
            $goods_spec_one = Db::name("goods_spec_one")->where("id in ($goods_spec_one_id)")->field("id,name")->select();
        }
        $goods_spec_two = array();
        if ($goods_spec_two_id) {
            $goods_spec_two = Db::name("goods_spec_two")->where("id in ($goods_spec_two_id)")->field("id,name")->select();
        }
        //用户是否收藏
        $is_shoucang = 0;
        if ($uid) {
            $usercollection = Db::name("usercollection")->where("userhome_id = {$uid} and goods_id = {$goods_id}")->find();
            if ($usercollection) {
                $is_shoucang = 1;
            }
        }
        //浏览记录
        if ($uid) {
            $goods_one_type_id = Db::name("goods")->where("id = {$goods_id}")->value("goods_one_type_id");
            $de = array();
            $de['userhome_id'] = $uid;
            $de['goods_one_type_id'] = $goods_one_type_id;
            $de['createtime'] = time();
            Db::name("userlike")->where("userhome_id = {$uid}")->where("goods_one_type_id = {$goods_one_type_id}")->delete();
            Db::name("userlike")->insert($de);
        }
        $data = array();
        $data['goods'] = $goods;
        $data['goods_spec_one'] = $goods_spec_one;
        $data['goods_spec_two'] = $goods_spec_two;
        $data['is_shoucang'] = $is_shoucang;
        return $data;
    }
}
